package com.safeneeds.linguimana.ser.impl;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.safeneeds.linguimana.dto.IpDataStorePort;
import com.safeneeds.linguimana.entity.PortGlutLog;
import com.safeneeds.linguimana.entity.PortVisitData;
import com.safeneeds.linguimana.entity.dao.IPortGlutDutyDao;
import com.safeneeds.linguimana.entity.dao.IPortGlutLogDao;
import com.safeneeds.linguimana.ser.IBgLogService;
import com.safeneeds.util.date.DateUtil;
import com.safeneeds.util.page.PageInfo;
import com.safeneeds.util.page.ser.IPageService;
@Service
@Transactional
public class BgLogService implements IBgLogService{
	@Resource(name="portGlutLogDao")
	private IPortGlutLogDao portGlutLogDao;
	@Resource(name="pageService")
	private IPageService pageService;
	@Override
	public void add(HttpServletRequest request) {

		//查询IP是否已存在
		String tempip = getIpAddr(request);
		if("0:0:0:0:0:0:0:1".equals(tempip)){
			tempip="127.0.0.1";
		}
		String todayTime= DateUtil.getDateByYMD();
		if(portGlutLogDao.existIpFromLog(tempip,todayTime)){
			//不存在 添加
			PortGlutLog log=new PortGlutLog();
			log.setIp(tempip);
			log.setTime(new Date());
			log.setRequestUrl(request.getRequestURI());
			portGlutLogDao.add(log);
		}
	}
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		} else {
			return request.getRemoteAddr();
		}
	}
	@Override
	public PageInfo listLogPage(PageInfo pageInfo,
			IpDataStorePort ipDataStorePort) {
		// TODO Auto-generated method stub
		
        pageInfo = portGlutLogDao.listLogPageDao(pageInfo,ipDataStorePort);
		
		pageInfo = pageService.getSQLPageInfo(pageInfo);
		return pageInfo;
	}

	public PortVisitData getVisitData() {
		PortVisitData visit=portGlutLogDao.getPortVisitData();
		return visit;
	}
	
	
}
